﻿using Microsoft.AspNetCore.Mvc;
using Single.Core.Service;
using Single.Sys.Entity;
using Single.WebApp.Components;
using System.Collections;

namespace Single.WebApp.Areas.Sys.Controllers
{
    [Area("sys")]
    public class RoleController : WorkController
    {
        public IActionResult Index()
        {
            return View();
        }

        public string Get(long id)
        {
            var entity = ServiceSysProps.SysRole.Get(id);

            return ServiceResult.SerializeData(entity);
        }

        public string GetData(int pageNum, int pageSize, string title, string remark)
        {
            var rows = ServiceSysProps.SysRole.GetPageList(pageNum, pageSize, title, remark, out int total);

            return ServiceResult.SerializeData(new { rows, total });
        }

        public string Save(SysRole entity)
        {
            return ServiceSysProps.SysRole.InsertOrUpdate(entity).Serialize();
        }

        public string Delete(long[] ids)
        {
            return ServiceSysProps.SysRole.Delete(ids).Serialize();
        }

        public string GetPower(long id)
        {
            var menulist = ServiceSysProps.SysMenu.GetAll();
            var menufunctionlist = ServiceSysProps.SysMenuFunction.GetAll();
            var rolemenufunctionlist = ServiceSysProps.SysRoleMenuFunction.GetByRoleId(id);

            List<Hashtable> rows = new List<Hashtable>();

            foreach (var menu in menulist)
            {
                Hashtable hash = new Hashtable
                {
                    { "Id", menu.Id },
                    { "Icon", menu.Icon },
                    { "Title", menu.Title },
                    { "Pid", menu.Pid }
                };

                var menufunctions = menufunctionlist.Where(m => m.MenuId == menu.Id);

                List<Hashtable> powerlist = new List<Hashtable>();

                foreach (var menufunction in menufunctions)
                {
                    Hashtable powerhash = new Hashtable
                    {
                        { "Id", menufunction.Id },
                        { "Icon", menufunction.Icon },
                        { "Type", menufunction.Type },
                        { "Title", menufunction.Title },
                        { "Exist", rolemenufunctionlist.Any(m => m.MenuFunctionId == menufunction.Id) }
                    };

                    powerlist.Add(powerhash);
                }

                hash.Add("PowerList", powerlist);

                rows.Add(hash);
            }

            return ServiceResult.SerializeData(new { rows });
        }

        public string SetPower(long roleId, long[] mfIds)
        {
            return ServiceSysProps.SysRoleMenuFunction.SetMenuFunction(roleId, mfIds).Serialize();
        }
    }
}